package com.tancire.net.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tancire.common.core.domain.entity.SysUser;
import com.tancire.common.core.redis.RedisCache;
import com.tancire.common.exception.net.NetActivityException;
import com.tancire.common.utils.DateUtils;
import com.tancire.common.utils.SecurityUtils;
import com.tancire.common.utils.StringUtils;
import com.tancire.net.domain.AuthInfo;
import com.tancire.net.domain.CrmCompany;
import com.tancire.net.domain.CrmCompanyTask;
import com.tancire.net.domain.ShopTask;
import com.tancire.net.mapper.ShopTaskMapper;
import com.tancire.net.service.IAuthInfoService;
import com.tancire.net.service.ICrmCompanyService;
import com.tancire.net.service.ICrmCompanyTaskService;
import com.tancire.net.service.IShopTaskService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 任务管理Service业务层处理
 *
 * @author chenchao
 * @date 2023-12-25
 */
@Service
public class ShopTaskServiceImpl implements IShopTaskService {

    @Resource
    private ShopTaskMapper shopTaskMapper;

    @Resource
    private ICrmCompanyService crmCompanyService;

    @Resource
    private IAuthInfoService authInfoService;

    @Resource
    private ICrmCompanyTaskService crmCompanyTaskService;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RedisCache redisCache;

    /**
     * 查询任务管理
     *
     * @param id 任务管理主键
     * @return 任务管理
     */
    @Override
    public ShopTask selectShopTaskById(Long id) {
        return shopTaskMapper.selectShopTaskById(id);
    }

    /**
     * 查询任务管理列表
     *
     * @param shopTask 任务管理
     * @return 任务管理
     */
    @Override
    public List<ShopTask> selectShopTaskList(ShopTask shopTask) {
        return shopTaskMapper.selectShopTaskList(shopTask);
    }

    /**
     * 新增任务管理
     *
     * @param shopTask 任务管理
     * @return 结果
     */
    @Override
    public int insertShopTask(ShopTask shopTask) {
        shopTask.setCreateTime(DateUtils.getNowDate());
        return shopTaskMapper.insertShopTask(shopTask);
    }

    /**
     * 修改任务管理
     *
     * @param shopTask 任务管理
     * @return 结果
     */
    @Override
    public int updateShopTask(ShopTask shopTask) {
        shopTask.setUpdateTime(DateUtils.getNowDate());
        return shopTaskMapper.updateShopTask(shopTask);
    }

    /**
     * 批量删除任务管理
     *
     * @param ids 需要删除的任务管理主键
     * @return 结果
     */
    @Override
    public int deleteShopTaskByIds(Long[] ids) {
        return shopTaskMapper.deleteShopTaskByIds(ids);
    }

    /**
     * 删除任务管理信息
     *
     * @param id 任务管理主键
     * @return 结果
     */
    @Override
    public int deleteShopTaskById(Long id) {
        return shopTaskMapper.deleteShopTaskById(id);
    }

    /**
     * 发起推广
     *
     * @param id
     */
    @Override
    public void promotionShopTask(Long id) {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 校验当前用户是否可以申请推广任务
        this.checkUserAuth(user);
        // 获取原始任务信息
        ShopTask shopTask = shopTaskMapper.selectShopTaskById(id);
        if (null != shopTask) {
            // 获取原始资源ID
            Long authId = shopTask.getAuthId();
            if (null == authId) {
                throw new NetActivityException("获取原始资源失败，请稍后重试");
            }
            // 查询原始资源信息
            AuthInfo authInfo = this.authInfoService.selectAuthInfoById(authId);
            // 先校验是不是已经推广
            CrmCompanyTask queryTask = new CrmCompanyTask();
            queryTask.setParentAuthCode(authInfo.getSourceCode());
            queryTask.setCompanyId(user.getUserId());
            List<CrmCompanyTask> crmCompanyTasks = this.crmCompanyTaskService.selectCrmCompanyTaskList(queryTask);
            if (ObjectUtil.isNotEmpty(crmCompanyTasks)) {
                throw new NetActivityException("资源已经推广，请勿重复操作");
            }
            RLock lock = redissonClient.getLock("OUT_AUTH_LIST");
            // 加锁，10秒自动释放
            lock.lock(10, TimeUnit.SECONDS);
            int baseNum = 0;
            String key = "OUT_AUTH_LIST_IDX";
            if (Boolean.TRUE.equals(redisCache.hasKey(key))) {
                int idx = redisCache.getCacheObject(key);
                baseNum = idx + 1;
            }
            redisCache.setCacheObject(key, baseNum);
            lock.unlock();
            // 初始化新编码
            String nCode = "TCU";
            StringBuilder numStr = new StringBuilder(baseNum + "");
            if (numStr.length() < 8) {
                int count = 8 - numStr.length();
                for (int i = 0; i < count; i++) {
                    numStr.insert(0, "0");
                }
            }
            nCode = nCode + numStr;
            // 先缓存原始code
            CrmCompanyTask task = new CrmCompanyTask();
            task.setParentAuthCode(authInfo.getSourceCode());
            // 在保存新code
            authInfo.setSourceCode(nCode);
            // 重新生成ID
            authInfo.setId(IdUtil.getSnowflakeNextId());
            // 标记为公司所属
            authInfo.setSourceBelong(1);
            // 保存所属公司
            authInfo.setBelongCompany(user.getUserId());
            authInfo.setBelongCompanyName(user.getNickName());
            this.authInfoService.insertAuthInfo(authInfo);
            // 生成任务数据
            task.setId(IdUtil.getSnowflakeNextId());
            task.setShopTaskId(shopTask.getId());
            task.setAuthId(authInfo.getId());
            task.setAuthCode(authInfo.getSourceCode());
            task.setAuthName(authInfo.getSourceName());
            task.setCompanyId(authInfo.getBelongCompany());
            task.setCompanyName(authInfo.getBelongCompanyName());
            task.setAuthPublicKey(authInfo.getSourcePublicKey());
            task.setTaskStatus(0);
            task.setCreateTime(new Date());
            task.setCreateBy(SecurityUtils.getUserId() + "");
            this.crmCompanyTaskService.insertCrmCompanyTask(task);
        }
    }

    /**
     * 校验是否可以推广
     *
     * @param user
     */
    private void checkUserAuth(SysUser user) {
        // 获取企业账号信息
        Long userId = user.getUserId();
        CrmCompany crmCompany = crmCompanyService.selectCrmCompanyById(userId);
        Integer miniAppStatus = crmCompany.getMiniAppStatus();
        if (null == miniAppStatus || miniAppStatus != 1) {
            throw new NetActivityException("请先在设置页面绑定小程序");
        }
        String liaisonPhone = crmCompany.getLiaisonPhone();
        if (StringUtils.isBlank(liaisonPhone)) {
            throw new NetActivityException("请先到设置中维护账户信息");
        }
    }
}
